package com.kkshop.gwt.registration;

import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.kkshop.gwt.base.Controller;
import com.kkshop.gwt.i18n.ApplicationResources;
import com.kkshop.gwt.widget.wizard.impl.stackpanel.StackPanelWizardWidget;

public class RegistrationController implements Controller {

    private static final String CONTAINER_ID = "registrationContainer";
    
    private static RegistrationController instance;
    
    private ApplicationResources resources = ApplicationResources.ApplicationResourcesHelper.getInstance().getResources();
    
    private DialogBox wizardDialog;
    private RegistrationView view;
    
    public RegistrationController() {
        instance = this;
    }
    
    public static RegistrationController getInstance() {
        return instance;
    }

    public void initialize() {
        view = new RegistrationView();
        view.getRegisterLink().addClickListener(new ClickListener() {
            public void onClick(Widget widget) {
                if(wizardDialog != null) {
                    return;
                }
                wizardDialog = new DialogBox();
                wizardDialog.setText(resources.registerWizardHeader());
                StackPanelWizardWidget wizardWidget = new StackPanelWizardWidget(getWizard());
                wizardWidget.setShowOnlyCurrentPage(true);
                wizardDialog.setWidget(wizardWidget.createWidget());
                wizardDialog.setSize("300px", "200px");
                wizardDialog.center();
            }
        });
        RootPanel.get(CONTAINER_ID).add(view.getWidget());
    }
    
    private RegistrationWizard getWizard() {
        return new RegistrationWizard(new RegistrationModel()) {
            public boolean finish() {
                boolean result = super.finish();
                if(result && wizardDialog != null) {
                    wizardDialog.hide();
                    wizardDialog = null;
                    return true;
                } else {
                    return false;
                }
            }

            public void cancel() {
                super.cancel();
                if(wizardDialog != null) {
                    wizardDialog.hide();
                    wizardDialog = null;
                }
            }
        };
    }
    
    public ApplicationResources getResources() {
        return resources;
    }

    public String getContainerId() {
        return CONTAINER_ID;
    }
}
